// Vue 2 插件 - WebSocketService.js
export default {
  install (Vue, options) {
    const clientId = Math.random().toString(36).substr(2)
    const wsUrl = options.url + clientId
    let ws = null
    let reconnectInterval = null
    let isReconnecting = false

    const connect = () => {
      ws = new WebSocket(wsUrl)
      Vue.prototype.$socket = ws
      ws.onopen = () => {
        console.log('WebSocket 连接成功')
        isReconnecting = false
      }

      ws.onclose = () => {
        console.log('WebSocket 关闭连接')
        if (!isReconnecting) {
          isReconnecting = true
          reconnect()
        }
      }

      ws.onerror = () => {
        console.error('WebSocket 连接错误')
        if (!isReconnecting) {
          isReconnecting = true
          reconnect()
        }
      }

      ws.onmessage = (message) => {
        // 处理消息
        console.log(message.data)
      }
    }

    const reconnect = () => {
      clearInterval(reconnectInterval)
      reconnectInterval = setInterval(() => {
        if (ws.readyState === WebSocket.CLOSED) {
          connect()
        } else {
          window.location.reload()
        }
      }, 5000) // 每5秒尝试重连一次
    }

    Vue.prototype.$webSocket = {
      connect,
      send (message) {
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(message)
        }
      },
      close () {
        if (ws) {
          ws.close()
        }
      }
    }
  }
}
